#! /bin/bash

declare APP_NAME=$1

if [ ! -n "$APP_NAME" ]; then
  echo " APP_NAME is empty, failure."
  exit 0
fi

echo ""
echo "${APP_NAME} starting deploy..."
echo ""


# 定义一个工作目录
declare path=$(cd `dirname $0`; pwd)
echo "current path is  :" ${path} 

# "/home/apps/server";
declare BASE_PATH=${path};
declare APP_PATH=${BASE_PATH}/${APP_NAME};

# zip file
declare APP_SRC_ZIP_NAME=${APP_PATH}/archv/${APP_NAME}-server-1.0-SNAPSHOT-cli.tar.gz
# echo ${APP_SRC_ZIP_NAME}

if [ ! -f "$APP_SRC_ZIP_NAME" ]; then
  echo "  源 ${APP_SRC_ZIP_NAME} 不存在, 退出."
  exit 0;
else
  echo "  源 ${APP_SRC_ZIP_NAME} 存在, 可以继续."
fi

# 定义时间
declare curr_datetime=date;

# 取ms
declare CUR_MS_NOW=`expr \`$curr_datetime +%N\` / 1000000`;
# format 3 digit
CUR_MS_NOW=$(printf "%03d\n" $CUR_MS_NOW);

# 取年月日_时分秒
declare CUR_YYYYMD_HMS="$(${curr_datetime} "+%Y%m%d_%H%M%S")";

# 合并后，得到 年月日_时分秒-ms
declare DATETIME=$CUR_YYYYMD_HMS-$CUR_MS_NOW;

# 目标目录
#declare APP_DST_PATH=${APP_PATH}/${APP_NAME};
#echo $APP_DST_PATH
declare DST_APP_PATH_DATE=${APP_PATH}/${APP_NAME}-${DATETIME};
if [ ! -d "${DST_APP_PATH_DATE}" ]; then
    echo "部署目录不存在：${DST_APP_PATH_DATE}"
    mkdir -p ${DST_APP_PATH_DATE}
fi

#echo "tar: ${APP_SRC_ZIP_NAME} - ${DST_APP_PATH_DATE}"
tar zxvf ${APP_SRC_ZIP_NAME} -C ${DST_APP_PATH_DATE}

# 备份源zip文件
mv ${APP_SRC_ZIP_NAME} ${APP_SRC_ZIP_NAME}_${DATETIME}

# 替换 conf 配件文件

echo "替换 conf 配件文件"
echo "${APP_PATH}/conf/ - > ${DST_APP_PATH_DATE}/${APP_NAME}-server-1.0-SNAPSHOT/"
cp ${APP_PATH}/conf/*.* ${DST_APP_PATH_DATE}/${APP_NAME}-server-1.0-SNAPSHOT/

# 休眠
sleep 1

if [ ! -d "${DST_APP_PATH_DATE}" ]; then

  echo "  部署 ${DST_APP_PATH_DATE} failure, please try later."
  exit 0;

else
    # 移除软链
    declare LINK_NAME=$APP_PATH/current;
    rm -rf ${LINK_NAME};
    echo   current: ${LINK_NAME};

    # 重新创建软链
    ln -s ${DST_APP_PATH_DATE} ${LINK_NAME};

    ${BASE_PATH}/restart.sh ${APP_NAME}

    echo "  部署 ${DST_APP_PATH_DATE} success."
    echo ""
    echo "end deploy."

fi
